package pub.cleangao.mqtt;

import com.vzenith.cloud.http.HttpClient;
import com.vzenith.cloud.http.HttpMethod;
import com.vzenith.cloud.http.HttpRequest;
import com.vzenith.cloud.http.HttpResponse;
import lombok.Getter;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;
@Component
public class VzDevices  {


    @Getter
    private Set<String> serialNo = new HashSet<>();

    @Value("${vzi-cloud.base-url}")
    private String baseUrl;

    @Value("${vzi-cloud.access-key-id}")
    private String accessKey;

    @Value("${vzi-cloud.access-key-secret}")
    private String accessKeySecret;



    public void init() throws Exception {
        serialNo.clear();
        queryByPage(1);
    }

    private void queryByPage(int page) {
        String path = "/openapi/v1/stp/user/devices";
        HttpClient httpClient = new HttpClient(baseUrl, accessKey, accessKeySecret);
        HttpRequest request = new HttpRequest(HttpMethod.GET, path);
        request.addParam("size", "10000");
        request.addParam("page", String.valueOf(page));
        HttpResponse response = httpClient.doRequest(request);
        if (response.getStatus() == 200) {
            JSONObject jsonObject = new JSONObject(response.getBodyStr());
            JSONArray jsonArray = jsonObject.getJSONArray("items");
            for (int j = 0; j < jsonArray.length(); j++) {
                JSONObject item = jsonArray.getJSONObject(j);
                if (item == null) {
                    continue;
                }
                String sn = item.getString("sn");
                serialNo.add(sn);
            }
            if (page == 1) {
                int total = jsonObject.getInt("total");
                int maxPageNum = (total + 9999) / 10000;
                for (int i = 2; i <= maxPageNum; i++) {
                    queryByPage(i);
                }
            }
        }
    }



}
